﻿using System;
using Android.App;
using Android.OS;
using AppRobot.Adapters;
using System.Collections.Generic;
using AppRobot.Models;
using AppRobot.Services;
using Android.Text;
using AndroidX.AppCompat.App;
using AndroidX.RecyclerView.Widget;
using Android.Widget;

namespace AppRobot
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        RecyclerView _recyclerViewInfo;
        Button _btnSend;
        EditText _editSend;

        InfoAdapter _infoAdapter;

        string[] _welcomeTips => Resources.GetStringArray(Resource.Array.WelcomeTips);

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            var toolbar = FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            _recyclerViewInfo = FindViewById<RecyclerView>(Resource.Id.recycler_view_info);
            var mLayoutManager = new LinearLayoutManager(this);
            _recyclerViewInfo.SetLayoutManager(mLayoutManager);
            _infoAdapter = new InfoAdapter(this, new List<TalkMessage>());
            _recyclerViewInfo.SetAdapter(_infoAdapter);

            var rnd = new Random();
            _infoAdapter.Add(new TalkMessage
            {
                Flag = TalkType.Receive,
                Content = _welcomeTips[rnd.Next(_welcomeTips.Length - 1)]
            });

            _btnSend = FindViewById<Button>(Resource.Id.btn_send);
            _btnSend.Enabled = false;
            _btnSend.Click += OnBtnSendClick;

            _editSend = FindViewById<EditText>(Resource.Id.edit_send);
            _editSend.AfterTextChanged += AfterTextChanged;
        }

        private void AfterTextChanged(object sender, AfterTextChangedEventArgs e)
        {
            _btnSend.Enabled = _editSend.Text.Trim().Length > 0;
        }

        private async void OnBtnSendClick(object sender, EventArgs e)
        {
            _infoAdapter.Add(new TalkMessage
            {
                Flag = TalkType.Send,
                Content = _editSend.Text.Trim()
            });

            var api = new ApiService();
            var strSend = _editSend.Text.Trim();
            _editSend.Text = string.Empty;

            var apiResponse = await api.GetAsyanc(strSend);
            if (apiResponse != null)
            {
                _infoAdapter.Add(new TalkMessage
                {
                    Flag = TalkType.Receive,
                    Content = apiResponse.Text
                });
                _recyclerViewInfo.SmoothScrollToPosition(_infoAdapter.ItemCount - 1);
            }
        }
    }
}

